import time
from urllib.parse import urlencode
import requests


def gen_secid(rawcode: str) -> str:
    '''
    生成东方财富专用的secid

    Parameters
    ----------
    rawcode : 6 位股票代码

    Return
    ------
    str: 指定格式的字符串

    '''
    # 沪市指数
    if rawcode[:3] == '000':
        return f'1.{rawcode}'
    # 深证指数
    if rawcode[:3] == '399':
        return f'0.{rawcode}'
    # 沪市股票
    if rawcode[0] != '6':
        return f'0.{rawcode}'
    # 深市股票
    return f'1.{rawcode}'


def get_k_history(code: str, date: str, klt: int = 101, fqt: int = 0):
    '''
    功能获取k线数据

    Parameters
    ----------
    code : 6 位股票代码
    date: 开始日期 例如 20200101
    klt: k线间距 默认为 101 即日k
        klt:1 1 分钟
        klt:5 5 分钟
        klt:101 日
        klt:102 周
    fqt: 复权方式
        不复权 : 0
        前复权 : 1
        后复权 : 2
    Return
    ------
    DateFrame : 包含股票k线数据
    '''
    EastmoneyKlines = {
        'f51': '日期',
        'f53': '收盘'


    }
    EastmoneyHeaders = {
        'Host': 'push2.eastmoney.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko',
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Referer': 'http://quote.eastmoney.com/center/gridlist.html',
    }
    fields = list(EastmoneyKlines.keys())
    columns = list(EastmoneyKlines.values())
    fields2 = ",".join(fields)
    secid = gen_secid(code)
    params = (
        ('fields1', 'f1,f2,f3,f4,f5,f6'),
        ('fields2', fields2),
        # ('beg', date),
        ('end', '20500101'),
        ('rtntype', '6'),
        ('secid', secid),
        ('klt', f'{klt}'),
        ('fqt', f'{fqt}'),
        ('lmt', f'{120}'),
        ('_', f'{int(time.time() * 1000)}'),

    )
    params = dict(params)
    # http://push2his.eastmoney.com/api/qt/stock/kline/get?
    # cb=jQuery1124009736917431894287_1621907252077
    # &secid=0.002508
    # &ut=fa5fd1943c7b386f172d6893dbfba10b
    # &fields1=f1,f2,f3,f4,f5,f6
    # &fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61
    # &klt=101
    # &fqt=0
    # &end=20500101
    # &lmt=120
    # &_=1621907252123
    base_url = 'https://push2his.eastmoney.com/api/qt/stock/kline/get'
    url = base_url+'?'+urlencode(params)
    print(url)
    json_response: dict = requests.get(
        url, headers=EastmoneyHeaders).json()

    data = json_response.get('data')
    if data is None:
        if secid[0] == '0':
            secid = f'1.{code}'
        else:
            secid = f'0.{code}'
        params['secid'] = secid
        url = base_url+'?'+urlencode(params)
        json_response: dict = requests.get(
            url, headers=EastmoneyHeaders).json()
        data = json_response.get('data')
    if data is None:
        print('股票代码:', code, '可能有误')
        return {}

    # klines = data['klines']
    #
    # rows = []
    # for _kline in klines:
    #
    #     kline = _kline.split(',')
    #     rows.append(kline)
    #
    # df = pd.DataFrame(rows, columns=columns)
    stock_name = data['name']
    for price_str in data['klines']:
        price_array = price_str.split(',')
        t_date, t_price = price_array[0], price_array[1]
        if t_date == date:
            return {'code': code, 'name': stock_name, 'date': t_date, 'price': t_price}

    return {}


if __name__ == "__main__":
    # 股票代码
    code = '002508'
    date = '2021-05-17'
    print(get_k_history(code, date))
